package com.juneyao.log.logcenter.scheduler;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author quanbiao
 * @date 2018-07-30
 * 链路日志，应用日志定时删除
 */
@Component
public class QuartzDeleteService {

    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger("QuartzDeleteService");

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 应用日志索引前缀
     */
    @Value("${elasticsearch.application.index.name.prefix}")
    private String APPLICATION_LOG_INDEX_PREFIX;

    /**
     * 链路追踪和应用日志只保存30天，因为是按天建立索引
     * 链路追踪格式 zipkin:span-2018-07-30
     * 每天凌晨1点执行
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void deleteTraceIndex(){
        //获取30天前的日期
        String oneMonthBeforeStr = new DateTime().minusMonths(1).toString("yyyy-MM-dd");
        //拼接索引名称
        String traceIndexName = "zipkin:span-" + oneMonthBeforeStr;
        //判断索引是否存在
        boolean traceIndexExists = elasticsearchTemplate.indexExists(traceIndexName);
        if(traceIndexExists){
            //删除索引
            elasticsearchTemplate.deleteIndex(traceIndexName);
            logger.info("链路追踪日志:" + traceIndexName + " 删除成功！！！");
        }
        //应用日志索引名称
        String appIndexName = APPLICATION_LOG_INDEX_PREFIX + oneMonthBeforeStr;
        //判断索引是否存在
        boolean appIndexExists = elasticsearchTemplate.indexExists(appIndexName);
        if(appIndexExists){
            //删除索引
            elasticsearchTemplate.deleteIndex(appIndexName);
            logger.info("应用日志:" + appIndexName + " 删除成功！！！");
        }
    }

}
